#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>
#include <cstring>
#include<unistd.h>

int main(){
    int socketfd=socket(AF_UNIX,SOCK_STREAM,0);
    if(socketfd==-1){
        return -1;
    }
    struct sockaddr_un server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sun_family=AF_UNIX;
    strncpy(server_addr.sun_path,"./test.sock",sizeof(server_addr.sun_path)-1);
    if (connect(socketfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        perror("连接失败");
        close(socketfd);
        return -1;
    }
    const char *s="Hello from client";
    write(socketfd,s,strlen(s));
    char buffer[1024];
    while(true){
        memset(buffer,0,1024);
        ssize_t n=read(socketfd,buffer,1024);
        if(n==-1){
            perror("读取失败");
            close(socketfd);
            return -1;
        }
        else if(n==0){
            std::cout<<"Server 关闭连接"<<std::endl;
            break;
        }
        else{
            std::cout<<"接收到消息: "<<buffer<<std::endl;
            std::cin>>buffer;
            write(socketfd,buffer,n);
        }
    }
    close(socketfd);
    return 0;
}